import Vue from 'vue';
import store from '../store'
import axios from 'axios'
import vueAxios from 'vue-axios';
import { ACCESS_TOKEN } from '@/store/mutation-types'
import notification from 'ant-design-vue/es/notification'

// 请求超时
axios.defaults.timeout = 5000;

// 基础URL
axios.defaults.baseURL = process.env.VUE_APP_API_BASE_URL,

// http request 拦截器
axios.interceptors.request.use(config => {
  const token = Vue.ls.get(ACCESS_TOKEN)
  if (token) {
    config.headers['Access-Token'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
  }
  return config
}, err);

// http response 拦截器
axios.interceptors.response.use(response => {
  return response.data;
}, err);

const err = (error) => {
  if (error.response) {
    const data = error.response.data
    const token = Vue.ls.get(ACCESS_TOKEN)
    if (error.response.status === 403) {
      notification.error({
        message: 'Forbidden',
        description: data.message
      })
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      notification.error({
        message: 'Unauthorized',
        description: 'Authorization verification failed'
      })
      if (token) {
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.reload()
          }, 1500)
        })
      }
    }
  }
  return Promise.reject(error)
}

Vue.use(vueAxios, axios);